package com.imooc;

import com.imooc.bean.Person;
import com.imooc.bean.User;
import org.junit.Test;

import java.util.*;

/**
 * @Date:2021/10/11/22:40
 * @Description:
 */
public class SetTest {

    @Test
    public void test01(){
        Set set = new HashSet();
        set.add(123);
        set.add(234);
        set.add(456);
        set.add(new Person("tom",20));
        System.out.println(set);


    }

    //LinkHashSet
    @Test
    public void test02(){
        Set set = new LinkedHashSet();
        set.add(123);
        set.add(234);
        set.add(456);
        set.add(new Person("tom",20));
        set.forEach(System.out::println);
//        System.out.println(set);


    }

    //TreeSet
    @Test
    public void test03(){


        Set set = new TreeSet();
        set.add(new User("ly",4));
        set.add(new User("li",12));
        set.add(new User("lu", 20));
        set.add(new User("lu", 26));
//        set.add(new Person("tom",20));
        set.forEach(System.out::println);
//        System.out.println(set);
    }


    //TreeSet 定制排序
    @Test
    public void test04(){
        //需要创建compare 对象
        Comparator objectComparator = new Comparator() {  //这种代码叫 匿名内部类，实例化新的对象
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof User && o2 instanceof User){
                    User u1 = (User) o1;
                    User u2 = (User) o2;

                    return -Integer.compare(u1.getAge(), u2.getAge());

                } else {
                  throw  new RuntimeException("对象不匹配");
                }
            }
        };

        Set set = new TreeSet(objectComparator);
        set.add(new User("ly",4));
        set.add(new User("li",12));
        set.add(new User("lu", 20));
        set.add(new User("lu", 26));
//        set.add(new Person("tom",20));
        set.forEach(System.out::println);
//        System.out.println(set);


    }


    //测试 Treemap
    @Test
    public void test05() {
        new TreeMap(new Comparator() { // 2021/10/15 这种写法是匿名内部类，实例化新对象
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof User && o2 instanceof User) {
                    User o11 = (User) o1;
                    User o22 = (User) o2;
                    return Integer.compare(o11.getAge(), o22.getAge());
                }
                throw new RuntimeException("输入的类型不匹配");
            }
        });


    }
}
